<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>支付页面</title>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .container {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            text-align: center;
            max-width: 400px;
            width: 100%;
        }
        .title {
            font-size: 24px;
            font-weight: bold;
            color: #333;
            margin-bottom: 20px;
        }
        .userid {
            background: #f5f5f5;
            padding: 15px;
            border-radius: 10px;
            margin: 20px 0;
            font-family: monospace;
            color: #666;
        }
        .btn {
            background: #07c160;
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 10px;
        }
        .btn:hover {
            background: #06ad56;
            transform: translateY(-2px);
        }
        .btn:active {
            transform: translateY(0);
        }
        .loading {
            display: none;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="title">微信支付</div>
        <div class="userid" id="useridDisplay">用户ID: 加载中...</div>
        <button class="btn" onclick="launchMiniProgram()">拉起微信小程序</button>
        <button class="btn" onclick="launchWechatPay()">微信支付</button>
        <div class="loading" id="loading">处理中...</div>
    </div>

    <script>
        // 获取 URL 参数
        function getQueryVariable(variable) {
            var query = window.location.search.substring(1);
            var vars = query.split("&");
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split("=");
                if (pair[0] == variable) {
                    return decodeURIComponent(pair[1]);
                }
            }
            return null;
        }

        // 页面加载完成后执行
        window.onload = function() {
            const userId = getQueryVariable('userid');
            
            if (userId) {
                document.getElementById('useridDisplay').textContent = `用户ID: ${userId}`;
                console.log('成功获取到 userid:', userId);
                
                // 存储 userid 供后续使用
                window.userId = userId;
            } else {
                document.getElementById('useridDisplay').textContent = '用户ID: 未获取到';
                console.error('未能获取到 userid');
            }
        };

        // 拉起微信小程序
        function launchMiniProgram() {
            const userId = window.userId;
            if (!userId) {
                alert('用户ID未获取到');
                return;
            }

            showLoading();

            // 检查是否在微信环境中
            if (typeof wx !== 'undefined' && wx.miniProgram) {
                // 在微信环境中，可以直接跳转到小程序
                wx.miniProgram.navigateTo({
                    url: `/pages/payment/index?userid=${userId}`,
                    success: function() {
                        console.log('成功跳转到小程序');
                        hideLoading();
                    },
                    fail: function(err) {
                        console.error('跳转小程序失败:', err);
                        hideLoading();
                        alert('跳转失败，请重试');
                    }
                });
            } else {
                // 不在微信环境中，尝试打开微信
                const appId = 'wx1234567890abcdef'; // 替换为你的小程序 appId
                const path = `pages/payment/index?userid=${userId}`;
                const url = `weixin://dl/business/?t=${encodeURIComponent(path)}`;
                
                // 尝试打开微信
                window.location.href = url;
                
                // 如果无法打开微信，提示用户
                setTimeout(function() {
                    hideLoading();
                    alert('请在微信中打开此页面');
                }, 2000);
            }
        }

        // 微信支付
        function launchWechatPay() {
            const userId = window.userId;
            if (!userId) {
                alert('用户ID未获取到');
                return;
            }

            showLoading();

            // 这里需要调用你的后端接口获取支付参数
            // 示例代码：
            fetch('/api/create-payment', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    userid: userId,
                    amount: 100 // 支付金额，单位分
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 调用微信支付
                    if (typeof wx !== 'undefined' && wx.chooseWXPay) {
                        wx.chooseWXPay({
                            timestamp: data.timestamp,
                            nonceStr: data.nonceStr,
                            package: data.package,
                            signType: data.signType,
                            paySign: data.paySign,
                            success: function(res) {
                                hideLoading();
                                alert('支付成功！');
                            },
                            fail: function(res) {
                                hideLoading();
                                alert('支付失败：' + res.errMsg);
                            }
                        });
                    } else {
                        hideLoading();
                        alert('请在微信中打开此页面进行支付');
                    }
                } else {
                    hideLoading();
                    alert('创建支付订单失败：' + data.message);
                }
            })
            .catch(error => {
                hideLoading();
                console.error('请求失败:', error);
                alert('网络请求失败，请重试');
            });
        }

        function showLoading() {
            document.getElementById('loading').style.display = 'block';
        }

        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
        }
    </script>
</body>
</html> 